package com.live.http.slider;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.jsoup.Connection;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class SaveFile {

	private String pageUrl;
	private String path;

	public SaveFile(String pageUrl, String path) {
		this.pageUrl = pageUrl;
		this.path = path;
	}
	public void save()throws Exception{
		
		
		
		Connection conn = ConnectionFactory.getConnection(pageUrl,5000);
		
		Document document=conn.get();
		
		Elements elements=document.select("div[class=content] img");
		int len=elements.size();
		
		Element element;
		
		for(int i=0;i<len;i++){
			element=elements.get(i);
			String picUrl=element.attr("src");
			final String purl=executePicUrl(picUrl);
			final String fileName=path+"/"+i+".jpg";
			try {
				savePic(purl, fileName);
			} catch (Exception e) {
				System.out.println("保存文件失败![src=" + purl + "] >" + e.getMessage());
			}
			
		}
	}


	public void savePic(String picUrl,String savePath) throws Exception {
		// FileChannel channel=new FileOutputStream(savePath).getChannel();
		BufferedOutputStream out = null;
		byte[] bit = getByte(picUrl);
		if (bit.length > 0) {
			try {
				out = new BufferedOutputStream(new FileOutputStream(savePath));
				out.write(bit);
				out.flush();
				System.out.println(savePath);
			} catch (Exception e) {
				System.out.println(savePath + "  fail");
				;
			} finally {
				if (out != null) {
					out.close();
				}
			}
		}

	}

	public byte[] getByte(String uri) throws Exception {
		// 模拟多个客户端，还是一个呢？自己选择吧！
		HttpClient client = new DefaultHttpClient();
		client.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
		HttpGet get = new HttpGet(uri);
		get.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
				5000);
		try {
			HttpResponse resonse = client.execute(get);
			if (resonse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity entity = resonse.getEntity();
				if (entity != null) {
					return EntityUtils.toByteArray(entity);
				}
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			client.getConnectionManager().shutdown();
		}
		System.out.println("获取文件失败！[url=" + uri + "]");
		return new byte[0];
	}
	/**
	 * 处理图片的地址
	 * 
	 * @param picUrl
	 * @return
	 */
	private String executePicUrl(String picUrl) {
//		return Constants.BASE_URL+picUrl;
		return picUrl;
	}

}
